//  this library.
import 'package:flutter/material.dart';
import 'package:hktk_app/model/practice/practice_question_model.dart';
import 'package:hktk_app/model/subject/question_collection_model.dart';
import 'package:hktk_app/model/subject/submit_paper_model.dart';
import 'package:hktk_app/pages/question/analysis_question_page.dart';

import 'package:hktk_app/util/view_util.dart';
import 'package:hktk_app/widget/page_title_widget.dart';
import 'package:hktk_app/widget/question/result_accuracy_widget.dart';
import 'package:hktk_app/widget/question/result_card_widget.dart';
import 'package:hktk_app/widget/question/result_exam_widget.dart';

/// 答题结果页面
class ResultPage extends StatefulWidget {
  /// 考试id
  final SubmitPaperModel submitModel;

  /// 获取试题答案
  final SubmitPaperModel paperRecords;

  const ResultPage({
    super.key,
    required this.submitModel,
    required this.paperRecords,
  });

  @override
  State<ResultPage> createState() => _ResultPageState();
}

class _ResultPageState extends State<ResultPage> {
  late BuildContext _context;

  /// 总题数
  late int _qCount;

  /// 做题数
  late int _doCount;

  /// 错题数
  late int _errorCount;

  /// 正确题数
  late int _successCount;

  @override
  void initState() {
    super.initState();
    debugPrint("resultPage 页面 -> initState 方法执行 ===> ");
    debugPrint("");
    _qCount = widget.submitModel.paperRecords?.qcount ?? 0;
    _doCount = widget.submitModel.paperRecords?.doCount ?? 0;
    _errorCount = widget.submitModel.paperRecords?.errorCount ?? 0;
    _successCount = _doCount - _errorCount;
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("resultPage 页面 -> build 方法执行 ===> ");
    debugPrint("");
    _context = context;
    return Scaffold(
      backgroundColor: colorWhite2,
      body: Column(
        children: [
          PageTitleWidget(name: "答题结果", pageContext: context),
          Expanded(
            child: Column(
              children: [
                Expanded(child: _listItem()),
                _bottomItem(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 主要内容显示
  _listItem() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16),
      child: MediaQuery.removePadding(
        removeTop: true,
        context: _context,
        child: ListView(
          children: [
            hiSpace(height: 30),
            ResultAccuracyWidget(
              accuracy: _getAccuracy(),
              paperName: widget.submitModel.paperRecords!.name!,
              date: widget.submitModel.paperRecords!.endTime!,
            ),
            hiSpace(height: 30),
            ResultExamWidget(
              total: _qCount,
              success: _successCount,
              error: _errorCount,
              time: _getTotalTime(),
            ),
            hiSpace(height: 30),
            ResultCardWidget(list: _getBogInfoModel()),
            hiSpace(height: 30),
          ],
        ),
      ),
    );
  }

  /// 计算正确率的方法
  int _getAccuracy() {
    double value = _successCount / _qCount;
    return (value * 100).ceil();
  }

  /// 计算用时时间
  int _getTotalTime() {
    int i = widget.submitModel.paperRecords?.seconds ?? 0;
    DateTime time = DateTime.fromMillisecondsSinceEpoch(i);
    return time.minute;
  }

  /// 答题卡相关数据
  List<Map<String, dynamic>> _getBogInfoModel() {
    List<Map<String, dynamic>> list = [];

    Map<String, RecordModel>? recordsData = widget.submitModel.records?.data;
    List<ContentCollection>? contentList =
        widget.paperRecords.collectStructure?.content;
    if (contentList != null) {
      for (int i = 0; i < contentList.length; i++) {
        ContentCollection collection = contentList[i];
        if (collection.qs != null) {
          List<Map<String, dynamic>> content2 = [];
          List<PracticeQuestionModel> modelList = collection.qs!;
          for (int j = 0; j < modelList.length; j++) {
            PracticeQuestionModel model = modelList[j];
            int type = 0;
            RecordModel? recordModel = recordsData?[model.id];
            if (recordModel != null) {
              if (recordModel.rt == true) {
                type = 1;
              } else if (recordModel.rt == false) {
                type = 2;
              }
            }
            content2.add({"sort": model.sort, "type": type});
          }
          list.add({"tyName": collection.tyName, "content": content2});
        }
      }
    }
    return list;
  }

  /// 底部组件
  _bottomItem() {

    return Container(

      // padding: EdgeInsets.only(bottom: bottom, left: 40, right: 40),
      padding: EdgeInsets.only(bottom: 5, left: 40, right: 40,top: 5),
      decoration: BoxDecoration(
        color: colorWhite1,
        boxShadow: [
          BoxShadow(
            color: colorBlack8,
            offset: Offset(0, -1),
            blurRadius: 0,
            spreadRadius: 0,
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _showBtn(true),
          _showBtn(false),
        ],
      ),
    );
  }

  /// 显示对应按钮
  _showBtn(bool showAll) {
    return GestureDetector(
      onTap: () {
        _onTapFunJx(showAll);
      },
      child: Container(

        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 5),
        decoration: BoxDecoration(
          color: showAll ? colorWhite1 : colorBlue1,
          borderRadius: BorderRadius.all(Radius.circular(44)),
          border: Border.all(color: colorBlue1, width: 1),
        ),
        child: Center(
          child: Text(
            showAll ? "全部解析" : "错题解析",
            style: TextStyle(
              fontSize: 22,
              fontWeight: FontWeight.w500,
              color: showAll ? colorBlue1 : colorWhite1,
            ),
          ),
        ),
      ),
    );
  }

  /// 全部解析点击
  _onTapFunJx(bool showAll) {
    // 跳转对应页面
    Navigator.pushNamed(context, "/analysis-question", arguments: {
      "submitPaper": widget.submitModel,
      "collectionModel": widget.paperRecords.collectStructure!,
      "type": showAll,
    });
  }
}
